<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/12/13
 * Time: 14:48
 */
namespace zhtfrontend\modules\sitepadapi\controllers;

use common\components\helpers\Fun;
use zhtfrontend\models\datas\ClassStudent;
use zhtfrontend\models\datas\OrderSales;
use zhtfrontend\models\datas\Sales;
use zhtfrontend\modules\sitepadapi\components\rest\ActivebackController;
use yii\data\ArrayDataProvider;
use yii\db\Query;
use yii\web\Response;
use zhtfrontend\models\datas\ClassLesson;
use yii\web\NotFoundHttpException;

class CustomerController extends ActivebackController
{
    public $modelClass = 'common\models\datas\Customer';

    public $serializer = [
        'class' => 'zhtfrontend\modules\sitepadapi\components\rest\Serializer',
        'collectionEnvelope' => 'items',
    ];

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $behaviors;
    }

    public function actions()
    {
        $actions = parent::actions();
        unset($actions['index'], $actions['create'], $actions['update'], $actions['delete'], $actions['view']);
        return $actions;
    }

    //管理员搜索会员
    public function actionFindbyqrcode($qrcode)
    {
        $modelClass = $this->modelClass;
        $model = $modelClass::findOne(['id' => $qrcode]);
        if (empty($model)) {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        $data['items'] = [
            'customer_id' => $model->id,
            'customer_name' => $model->name,
            'customer_img' => $model->logo,
            'customer_star_level' => $this->getStar(3),
            'customer_address' => '',
            'customer_tel' => $model->mobile,
            'customer_integral' => $model->integral
        ];
        return $data;
    }

    //管理员搜索会员  会员  积分管理（暂无）
    public function actionIntegral($customer_id)
    {

    }


    //管理员搜索会员  会员  账单明细
    public function actionBill($customer_id)
    {
        $data = '';
        $accountRecordData = (new Query())->select('*')->from('{{%order_sales}} os')
            ->leftJoin('{{%order}} o', 'o.id=os.order_id')
            ->where(['o.customer_id' => $customer_id])
            ->all(Fun::getSiteDb());
        foreach ($accountRecordData as $k => $v) {
            $data['order_data'][] = [
                'order_number' => $v['order_id'],//编号
                'order_title' => $v['title'],//订单名称
                'order_time' => \Yii::$app->formatter->asDatetime($v['created_at'], 'yyyy-MM-dd h:i:s'),//时间
                'total_money' => $v['total'],//金额
                'privilege_money' => $v['discount_pay'],//折扣
                'practical_money' => $v['actual_pay'],//实际支付
                'status' => $this->getUnique($v['id']),//状态
            ];
            $data['order_money_total'] = (new Query())->select('SUM(actual_pay)')->from('{{%order}}')
                ->where(['customer_id' => $customer_id])->column(Fun::getSiteDb())[0];//总金额*/
        }
        return $data;
    }

    //管理员搜索会员  会员  课程信息
    public function actionCourse($customer_id)
    {
        $data = '';
        $course = (new Query())->select(['os.sales_id as sales_id', 'os.title as title', 't.name as name', 'os.class_count as lesson',
            'os.id as order_sales_id'])
            ->from('{{%order}} o')
            ->leftJoin('{{%order_sales}} os', 'o.id=os.order_id')
            ->leftJoin('{{%teacher}} t', 'os.teacher_id=t.id')
            ->where(['o.customer_id' => $customer_id])
            ->groupBy('os.sales_id')
            ->orderBy('os.sales_id')
            ->all(Fun::getSiteDb());
        if (empty($course)) {
            try {
                throw new NotFoundHttpException('当前没有课程');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        foreach ($course as $k => $v) {
            $data[] = [
                'sales_id' => $v['sales_id'],
                'course_name' => $v['title'],
                'teacher' => $v['name'],
                'lesson' => $v['lesson'],
                'status' => $this->getCourseStatus($v['order_sales_id'])
            ];
        }

        return new ArrayDataProvider([
            'allModels' => $data,
            'pagination' => [
                'pageSize' => 20
            ]
        ]);
    }

    public function actionFindbysalesid($sales_id)
    {
        $model = Sales::findOne(['id' => $sales_id]);
        if ($model !== null) {
            $data['items'] = [
                'image' => isset($model->teacher) ? $model->teacher->img : '',
                'course_name' => $model->title,
                'course_modality' => isset($model->course) ? $this->getModality($model->course->teache_form) : '',
                'course_time' => isset($model->classroomAttr) ?
                    $this->getDay($model->classroomAttr->classday) . ' ' .
                    $this->getTime($model->classroomAttr->start_time) . '-' .
                    $this->getTime($model->classroomAttr->end_time) : '',
                'teacher_name' => isset($model->teacher) ? $model->teacher->name : '',
                'like' => 999,
                'mechanic' => isset($model->mechanic) ? $model->mechanic->name : '',
                'teacher_introduction' => isset($model->teacher) ? $model->teacher->description : '',
                'ability' => '',
                'time' => $this->getOrder($model)['all']['time'],
                'status' => $this->getOrder($model)['all']['status'],
                'course_details' => $model->description
            ];
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
        return $data;
    }

    public function actionFindbysales($sales_id)
    {
        $model = Sales::findOne(['id' => $sales_id]);
        if ($model !== null) {
            $data['items'] = [
                'image' => isset($model->teacher) ? $model->teacher->img : '',
                'course_name' => $model->title,
                'course_modality' => isset($model->course) ? $this->getModality($model->course->teache_form) : '',
                'course_time' => isset($model->classroomAttr) ?
                    $this->getDay($model->classroomAttr->classday) . ' ' .
                    $this->getTime($model->classroomAttr->start_time) . '-' .
                    $this->getTime($model->classroomAttr->end_time) : '',
                'teacher_name' => isset($model->teacher) ? $model->teacher->name : '',
                'like' => 999,
                'mechanic' => isset($model->mechanic) ? $model->mechanic->name : '',
                'teacher_introduction' => isset($model->teacher) ? $model->teacher->description : '',
                'ability' => '',
                'time' => $this->getOrder($model)['already'],
                'course_details' => $model->description
            ];
            return $data;
        } else {
            try {
                throw new NotFoundHttpException('信息不存在');
            } catch (NotFoundHttpException $e) {
                return ['status' => 0, 'message' => 'error', 'result' => $e->getMessage()];
            }
        }
    }

    protected function getModality($modality)
    {
        switch ($modality) {
            case 0:
                return '一对一';
                break;
            case 1:
                return '小班制';
                break;
            case 2:
                return '普通班';
                break;
        }
        return '';
    }

    protected function getDay($day)
    {
        switch ($day) {
            case 1:
                return '周一';
                break;
            case 2:
                return '周二';
                break;
            case 3:
                return '周三';
                break;
            case 4:
                return '周四';
                break;
            case 5:
                return '周五';
                break;
            case 6:
                return '周六';
                break;
            case 7:
                return '周日';
                break;
        }
        return '';
    }

    protected function getTime($time)
    {
        $currentTime = strlen($time) == 3 ? substr($time, 0, 1) . ':' . substr($time, 1) : substr($time, 0, 2) . ':' . substr($time, 2);
        return $currentTime;
    }

    protected function getOrder($data)
    {
        $timeArr = [];
        $classId = (new Query())->select('*')->from('{{%class_manage}}')->where(['code' => $data->arrange_course_id])->one(Fun::getSiteDb());
        $classLesson = ClassLesson::find()->where(['class_id' => $classId['class_id']])->orderBy('lesson_id ASC')->asArray()->all();
        $classLessonNum = (int)count($classLesson);
        $startEnd = \Yii::$app->formatter->asDate($classLesson[0]['class_date'], 'yyyy/MM/dd') . '-' .
            \Yii::$app->formatter->asDate($classLesson[$classLessonNum - 1]['class_date'], 'yyyy/MM/dd');
        $startEndDay = isset($data->classroomAttr) ? $this->getDay($data->classroomAttr->classday) : '';
        $upDown = isset($data->classroomAttr) && $data->classroomAttr->end_time <= 1300 ? '上午' : '下午';
        $startEndsTime = isset($data->classroomAttr) ? $this->getTime($data->classroomAttr->start_time) : '';
        $startEndeTime = isset($data->classroomAttr) ? $this->getTime($data->classroomAttr->end_time) : '';
        $already = $startEnd . ' ' . $startEndDay . $upDown . $startEndsTime . '-' . $startEndeTime;
        $salesData = Sales::find()->where(['course_id' => $data->course_id, 'teacher_id' => $data->teacher_id])->all();
        foreach ($salesData as $k => $v) {
            $courseDay = isset($data->classroomAttr) ? $this->getDay($data->classroomAttr->classday) : '';
            $courseStartTime = isset($data->classroomAttr) ? $this->getTime($data->classroomAttr->start_time) : '';
            $courseEndTime = isset($data->classroomAttr) ? $this->getTime($data->classroomAttr->end_time) : '';
            $timeArr[] = $courseDay . " " . $courseStartTime . ':' . $courseEndTime;
        }
        $currentOrderNum = OrderSales::find()->where(['sales_id' => $data->id])->count();
        $totalNum = isset($data->classroom) ? $data->classroom->max_count : '';
        return [
            'already' => $already,
            'all' => ['time' => $timeArr, 'status' => '已预约' . $currentOrderNum . '/' . $totalNum . '人']
        ];
    }

    public function getStatus($status)
    {
        switch ($status) {
            case 0:
                return '支付';
                break;
            case 1:
                return '被退货';
                break;
            case 2:
                return '退货';
                break;
            case 3:
                return '被换货';
                break;
            case 4:
                return '换货';
                break;
            case 5:
                return '预约';
                break;
            case 7:
                return '交定金';
                break;
            case 8:
                return '被扩科';
                break;
            case 9:
                return '扩科';
                break;
            case 10:
                return '转课';
                break;
            case 11:
                return '被退定金';
                break;
            case 12:
                return '退定金';
                break;
            case 13:
                return '被转化';
                break;
            case 14:
                return '转化';
                break;
            case 15:
                return '被续费';
                break;
            case 16:
                return '续费';
                break;
        }
    }

    public function getUnique($order_id)
    {
        $orderHistory = (new Query())->select('*')->from('{{%order_history}}')
            ->where(['order_id' => $order_id])->orderBy('id ASC')->all(Fun::getSiteDb());
        $endData = end($orderHistory);
        $state = $this->getStatus($endData['states']);
        return $state;
    }

    public function getCourseStatus($order_sales_id)
    {
        $status = '';
        $classStudent = ClassStudent::find()->where(['order_sales_id' => $order_sales_id])->one();
        if (!empty($classStudent)) {
            $classManageId = $classStudent->class_manage_id;
            $classLessonStatus = ClassLesson::find()->select('status')->where(['class_id' => $classManageId])->column();
            if (in_array(4, $classLessonStatus)) {
                $status = '已停课';
            } else {
                switch ($classStudent->status) {
                    case 0:
                        $status = '预约中';
                        break;
                    case 1:
                        $status = '学习中';
                        break;
                    case 2:
                        $status = '已结束';
                        break;
                }
            }
        } else {
            $status = '预约中';
        }
        return $status;
    }

    protected function getStar($star)
    {
        switch ($star) {
            case 1:
                return '一星级';
                break;
            case 2:
                return '二星级';
                break;
            case 3:
                return '三星级';
                break;
            case 4:
                return '四星级';
                break;
            case 5:
                return '五星级';
                break;
            case 6:
                return '六星级';
                break;
        }
    }

}